/**
 * ----------------------------------------------------------------------------
 * Copyright Jens Konopka
 * 
 * Alle Rechte vorbehalten.
 * Licence: Apache 2.0
 * ----------------------------------------------------------------------------
 *
 * created on 05.03.2012 by jkonopka
 */
package de.sql.toolkit.generator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author jkonopka
 * 
 */
public class InsertScriptValueGenerator implements IGenerator {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3542286673043879621L;
	private static final String YYYY_MM_DD = "yyyy-MM-dd";
	private List<Object> columns;

	/**
	 * @param columns
	 */
	public InsertScriptValueGenerator(List<Object> columns) {
		this.columns = columns;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.sql.toolkit.generator.IGenerator#generate()
	 */
	@Override
	public String generate() throws Exception {
		final StringBuilder sb = new StringBuilder();
		for (final Object column : columns) {
			final String value = createFieldValue(column);
			sb.append(value);
			sb.append(" , ");
		}
		sb.delete(sb.lastIndexOf(" , "), sb.length());
		return sb.toString();
	}

	/**
	 * @param value
	 * @return
	 * @throws Exception
	 */
	private String createFieldValue(final Object value) throws Exception {
		if (value == null) {
			return "null";
		} else if (value instanceof String) {
			return "'" + String.valueOf(value) + "'";
		} else if (value instanceof Number) {
			return String.valueOf(value);
		} else if (value instanceof Date) {
			final SimpleDateFormat df = new SimpleDateFormat(YYYY_MM_DD);
			final String format = df.format((Date) value);
			return createFieldValue(format);
		}
		throw new Exception(String.format("Not implemented type for value %s", value.toString()));
	}

}
